package com.heima.admin.service.impl;

import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //参数校验
        if (dto.getName() == null || dto.getPassword() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }
        //校验用户是否存在
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName, dto.getName());

        List<AdUser> list = list(wrapper);
        if (list != null && list.size() == 1) {
            AdUser user = list.get(0);
            String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes(StandardCharsets.UTF_8));
            if (user.getPassword().equals(md5Password)) {
                //登录成功
                HashMap<String, Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
                //将密码置空(安全考虑)
                user.setPassword("");
                user.setSalt("");
                map.put("user", user);
                return ResponseResult.okResult(map);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户不存在");
        }
    }
}
